package com.tsmti.webservice.util;

import com.alibaba.fastjson.JSON;
import com.tsmti.webservice.constants.RedisConstants;
import com.tsmti.webservice.database.DynamicDbDao;
import com.tsmti.webservice.entity.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.List;

/**
 * @Package：com.tsmti.webservice.util
 * @Class：DynamicDBUtils
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/7/9 17:31
 * @Company:
 * @Version：
 * @Modified By:
 */
public class DynamicDbUtils {

    public static DynamicDbDao getDynamicDbDao(String dbKey) {
        DynamicDbDao dynamicDBDao = new DynamicDbDao();

       DataSource dataSource = getDataSource(dbKey);
        if (dataSource == null) {
            return null;
        }
        dynamicDBDao.initJdbcTemplate(getDataSource(dataSource));
        return dynamicDBDao;
    }

    private static BasicDataSource getDataSource(DataSource dataSourceEntity) {
        BasicDataSource dataSource = new BasicDataSource();
        String driverClassName = dataSourceEntity.getDriverClass();
        String url = StringEscapeUtils.unescapeHtml4(dataSourceEntity.getUrl());
        String dbUser = dataSourceEntity.getDbUser();
        String dbPassword = dataSourceEntity.getDbPassword();

        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(dbUser);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }

    /***
     * 获取连接池
     * @param dbKey
     * @return
     */
    private static DataSource getDataSource(String dbKey){
        try {
            List<DataSource> list = JSON.parseArray((String)RedisUtils.getObject(RedisConstants.DATASOURCE_CACHE),DataSource.class);
            if(list != null && list.size() >0){
                for (DataSource dataSource:list){
                    if (dbKey.equals(dataSource.getDbKey())){
                        return dataSource;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
